package com.bigmi.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigmi.apis.article.ArticleClientIp;
import com.bigmi.common.cont.WemediaConstants;
import com.bigmi.common.exception.CustomException;
import com.bigmi.model.article.pojo.ApArticleConfig;
import com.bigmi.model.common.dtos.PageResponseResult;
import com.bigmi.model.common.dtos.ResponseResult;
import com.bigmi.model.common.enums.AppHttpCodeEnum;
import com.bigmi.model.wemedia.dtos.WmNewsDto;
import com.bigmi.model.wemedia.dtos.WmNewsPageReqDto;
import com.bigmi.model.wemedia.pojos.WmMaterial;
import com.bigmi.model.wemedia.pojos.WmNews;
import com.bigmi.model.wemedia.pojos.WmNewsMaterial;
import com.bigmi.model.wemedia.pojos.WmUser;
import com.bigmi.utils.thread.WmThreadLocalUtil;
import com.bigmi.wemedia.mapper.WmMediaMapper;
import com.bigmi.wemedia.mapper.WmNewsMapper;
import com.bigmi.wemedia.mapper.WmNewsMaterialMapper;
import com.bigmi.wemedia.service.WmNewsScanService;
import com.bigmi.wemedia.service.WmNewsService;
import com.bigmi.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMediaMapper wmMediaMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;
    //自动审核接口
    @Autowired
    private WmNewsScanService wmNewsScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    //feign接口调用
    @Autowired
    private ArticleClientIp articleClientIp;


    //条件查询分页列表
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.判断分页参数是否传递
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //获取登录人
        WmUser user = WmThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.条件查询
        IPage page =new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper =new LambdaQueryWrapper<>();
        //状态查询
        if (dto.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //频道查询
        if (dto.getChannelId() != null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //时间范围查询
        if (dto.getBeginPubDate() !=null && dto.getEndPubDate() != null) {
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //查询登录人
        //查询当前登录用户的文章
        queryWrapper.eq(WmNews::getUserId,user.getId());
        //按照时间发布倒序查
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        //返回
        page = page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        List records = page.getRecords();
        log.info(""+records);
        log.info(""+responseResult);
        return responseResult;
    }
    //发布修改保存为草稿
    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //判断条件
        //传参为空或者文章为空
        if (wmNewsDto == null || wmNewsDto.getContent() ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        /**
         * 1.保存或修改文章
         */
        WmNews wmNews =new WmNews();
        //属性复制只有类型相同才可以拷贝
        /**
         * wmNewsDto拷贝到wmNews
         * 封面图片无法拷贝 list转为string
         */
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        //图片list转为string
        if (wmNewsDto.getImages() !=null && wmNewsDto.getImages().size()>0){
            String images = StringUtils.join(wmNewsDto.getImages(), ",");
            wmNews.setImages(images);
        }
        //如果状态为-1，封面为自动
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO) ){
            wmNews.setType(null);
        }
        SaveUpdateNew(wmNews);
        /**
         *  //2.判断是否为草稿，如果是结束当前方法
         */
        if (wmNewsDto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        /**
         * 3.不是草稿，保存文章内容和图片的关系
         */
        //保存内容中的图片
        List<String> image= cotentInfo(wmNewsDto.getContent());
        //保存文章
        saveContent(image,wmNews.getId());
        /**
         * 4.不是草稿，保存封面图片于文章关系
         * 如当前布局为自动，自动匹配内容图片
         */
        SaveInfoCover(wmNewsDto,wmNews,image);
        //审核文章
       // wmNewsScanService.ScanWmNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }




    /**
     * 保存和修改文章
     * wmNews中id为空则文章不存在
     * id不为空则文章存在，文章为修改
     * @param wmNews
     */
    private void SaveUpdateNew(WmNews wmNews) {
        //补全参数，wmNews中没有的参数，
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //默认上架文章
        wmNews.setEnable((short) 1);
        //判断id是否为空
        if(wmNews.getId() == null){
            save(wmNews);
        }else {
            //修改文章图片，文章和图片关系
            //查相关id
            LambdaQueryWrapper<WmNewsMaterial> wrapper =new LambdaQueryWrapper<>();
            wrapper.eq(WmNewsMaterial::getId,wmNews.getId());
            //删除图文关系表
            wmNewsMaterialMapper.delete(wrapper);
            //修改
            updateById(wmNews);
        }
    }
    //前端集合list图片和内容
    //提取内容当中的图片
    private List<String> cotentInfo(String content) {
        //在内容集合中选出图片，放入新的集合
        ArrayList<String> Url= new ArrayList<>();
        /**
         * JSON.parseArray
         * json数据转集合
         */
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                String imageUrl = (String) map.get("value");
                Url.add(imageUrl);
            }
        }
        return Url;
    }

    //保存文章素材图片和文章的关系
    private void saveContent(List<String> image, Integer newId) {
        //保存关系，在关系表,内容引用
        SaveInfo(image,newId,WemediaConstants.WM_CONTENT_REFERENCE);
    }
    //保存文章图片以及封面图片与素材到数据库中
    private void SaveInfo(List<String> image, Integer newId, Short type) {
        if (image!=null && !image.isEmpty()){
            //根据image(url)查询id
            LambdaQueryWrapper<WmMaterial> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.in(WmMaterial::getUrl,image);
            List<WmMaterial> wmMaterials = wmMediaMapper.selectList(queryWrapper);
            //判断素材是否有效
            if(wmMaterials ==null || wmMaterials.size()==0){
                //素材引用失效，进行数据回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            //传入图片数量与保存图片数量有误
            if (image.size()!=wmMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            //在集合中拿出id
            List<Integer> idList = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //批量保存
            wmNewsMaterialMapper.saveRelations(idList,newId,type);
        }

    }
    //如果当前封面为自动，匹配封面类型数据

    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     *      * 匹配规则：
     *      * 1，如果内容图片大于等于1，小于3  单图  type 1
     *      * 2，如果内容图片大于等于3  多图  type 3
     *      * 3，如果内容没有图片，无图  type 0
     *      *
     *      * 第二个功能：保存封面图片与素材的关系
     * @param wmNewsDto
     * @param wmNews
     * @param image
     */
    private void SaveInfoCover(WmNewsDto wmNewsDto, WmNews wmNews, List<String> image) {

        List<String> dtoImages = wmNewsDto.getImages();
        //如果为自动，则设置封面类型数据
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //多图
            if (image.size()>=3){
                //设置type为3
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                dtoImages = image.stream().limit(3).collect(Collectors.toList());
                //单图
            }else if (image.size()>=1 && image.size()<3){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                dtoImages = image.stream().limit(1).collect(Collectors.toList());
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //修改文章
            if (dtoImages!=null && dtoImages.size()!=0){
                wmNews.setImages(StringUtils.join(image,","));
            }
            updateById(wmNews);
            //保存封面图片和与素材关系
            if (dtoImages!=null && dtoImages.size()>0){
               SaveInfo(dtoImages,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
            }
        }
    }
    /**
     * 编辑查看文章
     */
    public ResponseResult one(int id){
        log.info(""+id);
        if (id!=0 ) {
           /* LambdaQueryWrapper<WmNews> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(WmNews::getId, id);*/
            WmNews wmNews = wmNewsMapper.selectById(id);
            log.info(""+wmNews);
            return ResponseResult.okResult(wmNews);

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

    }
    //删除文章并且删除相应关系表
    @Override
    public ResponseResult del_news(int id) {
        if (id !=0){
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper =new LambdaQueryWrapper<>();
            LambdaQueryWrapper<WmNewsMaterial> eq = queryWrapper.eq(WmNewsMaterial::getNewsId, id);
            //查询文章id的关系表
            List<WmNewsMaterial> wmNewsMaterialList = wmNewsMaterialMapper.selectList(eq);
            //查询文章id
            LambdaQueryWrapper<WmNews> wrapper =new LambdaQueryWrapper<>();
            wrapper.eq(WmNews::getId,id);
            WmNews wmNews = wmNewsMapper.selectOne(wrapper);

            System.out.println(wmNews);
            if (wmNewsMaterialList.size() != 0) {
                List<Integer> collect = wmNewsMaterialList.stream().map(WmNewsMaterial::getId).collect(Collectors.toList());
                for (Integer integer : collect) {
                    System.out.println("================"+integer);
                }
                //删除对应的文章图片关系表
                wmNewsMaterialMapper.deleteBatchIds(collect);
                //删除文章
                wmNewsMapper.deleteById(id);
                //删除app端文章
                articleClientIp.del(wmNews.getArticleId());
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }else {
                //删除文章后删除对应的文章图片关系表
                wmNewsMapper.deleteById(id);
                //删除app端文章
                articleClientIp.del(wmNews.getArticleId());
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }

    @Override
    public ResponseResult down_or_up(WmNewsDto wmNewsDto) {
        if (wmNewsDto != null) {
            Integer id = wmNewsDto.getId();

            Short enable = wmNewsDto.getEnable();

            //查询文章状态,不是上下架状态
            LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<WmNews> eq = queryWrapper.eq(WmNews::getEnable, enable);
            List<WmNews> wmNews = wmNewsMapper.selectList(eq);

            List<Short> collect = wmNews.stream().map(WmNews::getEnable).collect(Collectors.toList());
            for (Short integer : collect) {
                if (integer != 0 && integer != 1) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章不是上架状态不能操作");
                }
            }
            //修改自媒体端上下架状态
            WmNews wmNew = new WmNews();
            wmNew.setId(wmNewsDto.getId());
            wmNew.setEnable(enable);
            wmNewsMapper.updateById(wmNew);

            LambdaQueryWrapper<WmNews> wrapper = queryWrapper.eq(WmNews::getId, id);
            WmNews news = wmNewsMapper.selectOne(wrapper);
            Long articleId = news.getArticleId();
            //查询app端文章上架状态并且修改
            articleClientIp.upAndDown(articleId);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
